import path = require("path");
import fs = require("fs");
import { MD5, enc } from "crypto-js";
import translate from "./translate";
import _ from "lodash";

interface Params {
  languages: Array<string>; //语种类型集合
  appId: string; //应用id
  key: string; //应用密钥
  config_path: string;
  path: string;
  ProjectInit: any; //项目初始化工具实例对象
}
interface Keys {
  keyName: string;
  value: string;
  language?: string;
}
let config: any;

interface WordsKey {
  name: string;
  value: string | number;
}
export type WordsKeys = Array<WordsKey>;
/**
 * 将单词转换为统一格式
 */
function formatKey(words: Array<string> | string | object): WordsKeys {
  let list: WordsKeys = [];
  _.castArray(words).forEach((word) => {
    if (typeof word == "object")
      for (var key in word)
        list.push({
          name: key,
          value: word[key],
        });
    else
      list.push({
        name: generateUniqueVarName(word),
        value: word,
      });
  });
  return list;
}
/**
 * 获取代码需要翻译的单词
 * @param {string} code 代码文本
 * @param {RegExp} regex 代码文本
 * @returns {Array<string>}
 */
function getWords(code, regex = /\$t\((['"].*?['"]|\d+)\)/g) {
  // 使用正则表达式匹配 lang('xxx') 或 lang(123) 形式的调用
  const matches = code.match(regex);
  let words = [];
  if (matches) {
    words = (matches || [])
      .map((match: string) => {
        if (match) {
          let result = match.match(/\((['"].*?['"]|\d+)\)/);
          return result ? result[1].slice(1, -1) || null : null;
        }
        return null;
      })
      .filter((item) => item);
  }
  return words;
}
/**
 *
 * @param {WordsKeys} words 原始文本
 * @param {Array<string>} languages
 */
async function transform(words: WordsKeys, config: any) {
  let tasks = [];
  if(words.length)
    for(let i=0,len=config.languages.length;i<len;i++){
      let language=config.languages[i]
      tasks.push({
        language,
        list: await translate(words, language, config),
      });
    }
 
  return tasks;
}
/**
 * 根据翻译文本生成变量名
 * @param text
 * @param filePath
 * @param isWrite
 * @returns
 */
function generateUniqueVarName(multiLangText: string) {
  // 使用当前时间戳和文本的哈希值来增加唯一性
  const hash = MD5(multiLangText).toString(enc.Hex);
  return `v_${hash}`;
}

/**
 * 根据键值查找键名
 * @param obj 原始对象
 * @param value 查找值
 * @returns
 */
function findKeyByValue(obj: any, value: any): string {
  for (let key in obj) {
    if (obj[key] == value) {
      return key;
    }
  }
  return ""; // 如果未找到匹配的值，则返回 null
}

export { transform, getWords, formatKey };
